﻿
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_File_GetRootDirectory_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_File_GetRootDirectory_V2];
GO

CREATE PROCEDURE [dbo].[sproc_File_GetRootDirectory_V2]
    @ownerId     int,
    @directoryId int output
AS
BEGIN
SET NOCOUNT ON;

-- get the id of the existing root directory
SELECT @directoryId = DirectoryId
    FROM dbo.UDS_File_Directory
    WHERE OwnerId = @ownerId AND ParentDirectoryId = DirectoryId;

IF ( @@ROWCOUNT = 0 )
BEGIN
    -- create the root directory then
    SET IDENTITY_INSERT dbo.UDS_File_Directory ON
    
    SELECT @directoryId = ident_current(N'dbo.UDS_File_Directory') + 1;
    INSERT INTO dbo.UDS_File_Directory (DirectoryId, ParentDirectoryId, OwnerId, [Name] )
        VALUES ( @directoryId, @directoryId, @ownerId, N'根目录' );
    
    SET IDENTITY_INSERT dbo.UDS_File_Directory OFF
END;

-- get the information of the root directory
SELECT *
    FROM dbo.UDS_File_Directory
    WHERE DirectoryId = @directoryId;

RETURN 0;
END
GO

